//规则, 组件名字驼峰, 元素标签中划线分割, 两者映射缺一不可.
angular.module("app").component("winitPdmNeed", {
  templateUrl: getTemplateUrl("matrix/component/tpl/winitPdmNeed.html"),
  bindings: {
    pdmList:"<",
    need: "<",
    issueList: "<",
    refValue: "<",
    saveNeed:"&"
  },
  controller: function(
    $http,
    $rootScope,
    $scope,
    $element,
    $attrs,
    $modal,
    $filter,
    $timeout,
    lodash
  ) {
      var ctrl = this;
      $scope.info={need:{}}
      ctrl.info = { cycleStatus: [{ crtname: "天", value: "day" }, { crtname: "周", value: "week" }, { crtname: "月", value: "month" }], statusOpen: true, weekArray: [], crtItemDate: "", selIsuue: {}, returnIssues: [], tipsIssue: true, isAffirmed: false }; //pdm是否确认的标记
      //获取pdm权限
      $scope.isPdm = $rootScope.isUserCanOperateByRole("pdm");

      $scope.isVisible=true
      //页面组件的控制
      $scope.isPdmAble = false;
      $scope.isCommited = false; //pdm是否完成需求确认
      //管理员权限
      $scope.isAdmin = $rootScope.isUserCanOperateByRole("admin");


      $scope.pdmManager = function() {
        //获取需求状态
        $scope.info.needStatus = ctrl.need.status == "ACCEPT" ? true : false;

        if ($scope.isPdm && $scope.info.needStatus) {
          $scope.isPdmAble = false;
          $scope.isCommited = false;
        } else {
          $scope.isPdmAble = true;
          $scope.isCommited = true;
        }
      };


      //确定pdm是否已经完成
      $scope.commit = function () {
          var filter = config_need_status.filter(function (a) {
              return a.key == ctrl.need.status
          })
          if (filter[0]) {
              if (filter[0].index >= 4) {
                  $scope.isCommited = true
                  $scope.isVisible=true
              } else {
                  if (filter[0].index <=2) {
                      $scope.isVisible = false
                  } else {
                      if ($scope.isPdm) {
                          $scope.isCommited = false
                          $scope.isVisible=true
                      } else {
                          $scope.isCommited = true
                          $scope.isVisible = false
                      }
                      if($scope.isAdmin){
                          $scope.isCommited = true
                          $scope.isVisible = true
                      }
                  }
              }
          }
      }

      //获取pdm的负责人
      $scope.getNeedPdms = function() {
          if (ctrl.need.needPdm && ctrl.need.needPdm.length > 0) {
              var datas = ctrl.need.needPdm;
              ctrl.need.needPdmNames = "";
              datas.forEach(function (a) {
                  ctrl.need.needPdmNames += a.realname + "|";
              });
              ctrl.need.needPdmNames = ctrl.need.needPdmNames.substring(0, ctrl.need.needPdmNames.lastIndexOf("|"));
          }
          ;
      }
      //获取需求类型
      $scope.getPdmNeedTypeStr = function() {
          if (ctrl.need.pdmNeedType && ctrl.need.pdmNeedType.length >0) {
              var pdmNeedType = ctrl.need.pdmNeedType;
              config_pdmNeedTypes.forEach(function (a) {
                  if (a.key == pdmNeedType) ctrl.need.pdmNeedTypeStr = a.value;
              });
          }
          ;
      }
      //需求时间的格式化
      $scope.fomatPdmClearTime= function(){
          $scope.format = 'yyyy-MM-dd';
          ctrl.need.pdmClearTimeStr = $filter('date')(ctrl.need.pdmClearTime, $scope.format);
      }

      //获取优先级字符串
      $scope.getPdmPriorityStr = function() {
          var value = ctrl.need.pdmPriority;
          if (value >= 4) ctrl.need.pdmPriorityStr = "高";
          if (value >= 3) ctrl.need.pdmPriorityStr = "较高";
          if (value >= 2) ctrl.need.pdmPriorityStr = "中";
          if (value >= 1) ctrl.need.pdmPriorityStr = "较低";
          ctrl.need.pdmPriorityStr = "低";
      };

      $scope.commit();
      $scope.getPdmNeedTypeStr();
      $scope.pdmManager();
      $scope.getNeedPdms()
      $scope.fomatPdmClearTime()
      $scope.getPdmPriorityStr()



      ctrl.$onChanges = function() {
          $scope.pdmManager();
          $scope.getNeedPdms()
          $scope.getPdmNeedTypeStr();
          $scope.fomatPdmClearTime();
          $scope.getPdmPriorityStr()
          $scope.commit();
          setExpectedSchedule(ctrl.need);
          var cycleItem = lodash.findWhere(ctrl.info.cycleStatus, {
              value: ctrl.need.cycleStatus
          });
          ctrl.need.sltCycleStatus = cycleItem;
      };



      if (ctrl.need.needPdm) {
        if (ctrl.need.needPdm.length == 0) {
          ctrl.need.needPdm = [{ account: getUserAccount(), crtname: getUserName(), realname: getUserName() }];
        }
      }


      getDemand();
      // 需求完成
      getPurpose();

      if (ctrl.refValue == undefined) {
        ctrl.refValue = 0;
      }

      function getDemand() {
        var url = "../data/objectiveState.json";
        $http.get(url).success(function(result) {
          if (result.code == "0") {
            //退回
            ctrl.info.returns = result.data.RETURN;
            angular.forEach(ctrl.info.returns, function(ret) {
              ret.check = false;
            });
            //PDMBRDTYPE类型数据
            ctrl.info.pdmBrdTypes = result.data.PDMBRDTYPE;
            //系统数据
            ctrl.info.syss = result.data.SYS;
            angular.forEach(ctrl.info.syss, function(sys) {
              sys.check = false;
            });
          } else {
            $rootScope.toasterWarningInfo("获取目的状态有误！");
          }
        });
      }

      function getPurpose() {
        ctrl.info.completes = $rootScope.getSysConfigList("NEED_PURPOSE");
      }

      ctrl.showNumner = function() {
        if (ctrl.need.sltCycleStatus) {
          var sltCycleStatus = ctrl.need.sltCycleStatus.value == "day" ? 1 : ctrl.need.sltCycleStatus.value == "week" ? 5 : 20;
        } else {
          var sltCycleStatus = 1;
        }
        var day = (Number(ctrl.need.pdmCount) + Number(ctrl.need.uiCount) + Number(ctrl.need.devCount) + Number(ctrl.need.qaCount)) * Number(ctrl.need.cycle) * Number(sltCycleStatus);
        ctrl.cost = day * 500 || 0;
        return day || 0;
      };

      ctrl.costLowerFee = function() {
        return (ctrl.refValue == 0 ? 0 : ctrl.cost / (ctrl.refValue * 10000)).toFixed(2);
      };

      $scope.switchFallback = function(isFallback) {
        if (isFallback) {
          ctrl.need.isComplete = false;
          ctrl.need.completeReason = "";
          getAllIssues();
        }
        if (ctrl.issueList && ctrl.issueList.length > 0) {
          if (ctrl.issueList[0].reqCount > 0) {
            $rootScope.toasterWarningInfo("【立项开发】状态下用户故事不为空的不能回退！");
            ctrl.need.pdmIsReturn = false;
            return false;
          }
        }
        if (!isFallback) {
          return false;
        }
      };

      $scope.switchComplete = function(isComplete) {
        if (isComplete) {
          ctrl.need.pdmIsReturn = false;
          ctrl.need.fallbackReason = "";
        }
      };

      // 设置排期时间
      function setExpectedSchedule(need) {
        ctrl.info.weekArray = getWeekArray();
        var weekItem = lodash.findWhere(ctrl.info.weekArray, {
          ms: need.expectedTime
        });
        ctrl.info.crtItemDate = weekItem;
      }

      // 设置选中时间
      $scope.selectDateItem = function(data) {
        ctrl.need.expectedTime = data.ms || "";
      };

      //选中用户故事
      $scope.selectIssueItem = function(data) {
        // ctrl.need.expectedTime = data.ms || "";
      };

      $scope.returnChecked = function(ret) {
        console.log("return-----" + JSON.stringify(ret));
        var datas = ctrl.info.returns.filter(function(a) {
          return a.key == ret.key;
        });
        if (datas && datas.length > 0) {
          ret.check = false;
          ctrl.need.fallbackReason = ret;
          console.log("ret    " + JSON.stringify(ctrl.need.fallbackReason));
        }
      };

      //选中回退理由
      $scope.selecRtn = function(rtn) {
        console.log("回退理由---" + JSON.stringify(rtn));
        ctrl.need.sltRtn = [];
        rtn.check = !rtn.check;
          ctrl.need.fallbackReason=""
        angular.forEach(ctrl.info.returns, function(objective) {
          if (objective.check) {
            ctrl.need.sltRtn.push(objective);
            ctrl.need.fallbackReason+=objective.value+","
          }
        });
        ctrl.need.fallbackReason=ctrl.need.fallbackReason.substring(0,ctrl.need.fallbackReason.lastIndexOf(','))
      };

      //添加回退的故事用例
      $scope.addReturnIssue = function() {
        if (ctrl.info.selIsuue) {
            ctrl.info.tipsIssue = false;
            ctrl.info.returnIssues.push(ctrl.info.selIsuue);
            if (ctrl.info.issues) {
                ctrl.info.issues = ctrl.info.issues.filter(function (a) {
                    if (a.id != ctrl.info.selIsuue.id) {
                        return a;
                    }
                });
            }
        }
      };

      //打开用户故事的模态框
      $scope.openNeedModal = function(info) {
        info.issueModal = true;
        var modalInstance = $modal.open({
          animation: true,
          templateUrl: getTemplateUrl(
            "matrix/component/tpl/updateModel.html"
          ),
          controller: "openNeedCtrl",
          backdrop: true,
          resolve: {
            items: function() {
              return info;
            }
          }
        });
        //点击modal新增后，把feature值传过来
        modalInstance.result.then(function(reason) {
          cancelModal(reason);
        });
        function cancelModal(reason) {
          console.log("取消");
        }
      };


      ctrl.info.isEnded=false
      //pdm准备确认需求
      $scope.prepareCommit=function (value) {
          ctrl.info.isEnded=value
          $scope.isPdmAble=value
      }

      $scope.isDisabled = false;
      $scope.pdmEdit=function(){
          $scope.isDisabled = true;
          $scope.isCommited=false
          ctrl.info.isEnded = false;
          $scope.isPdmAble = false;
          $timeout(function () {
              $scope.isDisabled = false;
          },1000)

      }

      //需求确认
      $scope.pdmAffirm = function() {
        console.log("pdm评审完成----");
        if (!ctrl.need.needPdm) {
          ctrl.info.isEnded = false;
          $scope.isPdmAble = false;
          $rootScope.toasterWarningInfo("负责人不能为空");
          return;
        }
        if (!ctrl.need.pdmNeedType) {
          ctrl.info.isEnded = false;
          $scope.isPdmAble = false;
          $rootScope.toasterWarningInfo("需求类型不能为空");
          return;
        }

        if (!ctrl.need.pdmDesc) {
          ctrl.info.isEnded = false;
          $scope.isPdmAble = false;
          $rootScope.toasterWarningInfo("备注不能为空");
          return;
        }

        if (ctrl.need.pdmIsReturn) {
          console.log("是否是回退--" + ctrl.need.pdmIsReturn);
          if (!ctrl.need.sltRtn || ctrl.need.sltRtn == 0) {
            $rootScope.toasterWarningInfo("请选择回退理由");
            ctrl.info.isEnded = false;
            $scope.isPdmAble = false;
            return;
          }
          if (!ctrl.info.selIsuue) {
            $rootScope.toasterWarningInfo("请选择用户故事");
            ctrl.info.isEnded = false;
            $scope.isPdmAble = false;
            return;
          }
        } else if (ctrl.need.isComplete) {
        } else {
          if (!ctrl.need.pdmCount && !ctrl.need.uiCount && !ctrl.need.devCount && !ctrl.need.qaCount) {
            ctrl.info.isEnded = false;
            $scope.isPdmAble = false;
            $rootScope.toasterWarningInfo("人工数不能全为0");
            return;
          }
          if (ctrl.need.cycle == 0) {
            ctrl.info.isEnded = false;
            $scope.isPdmAble = false;
            $rootScope.toasterWarningInfo("时长不能为0");
            return;
          }
        }

        var confirmParams = { titleData: "提示", bodyData: "确定需求确认结束" };
        $rootScope.confirmWindow(confirmParams, function(data) {
          if (data) {
            $scope.isPdmAble = true;
            $scope.isCommited = true;
            if (ctrl.need.pdmIsReturn) {
              ctrl.need.status = "CLOSED";
            } else if (ctrl.need.isComplete) {
              ctrl.need.status = "CLOSED";
            } else {
              ctrl.need.status = "CONFIRM";
            }
            ctrl.info.isEnded = true;
            ctrl.saveNeed();
          }
        });
      };

      //请求后端 获取所有的用户故事 用于需求回退
      function getAllIssues() {
        var url = matrix_product_url + "/issue/getIssues";
        var urlArray = [{ type: "reserveHabit", param: 1 }, { type: "tokenId", param: getTokenId() }];
        url = $rootScope.setUrlParams(url, urlArray);
        $http.get(url).success(function(result) {
          if (result.code == "0") {
            if (result.data) {
              var olddata = result.data;
              olddata.forEach(function(a) {
                a.crtname = a.content;
                return a;
              });
              ctrl.info.issues = olddata;
            } else {
              $rootScope.toasterErrorInfo("获取issue列表数据错误！");
            }
          } else {
            $rootScope.toasterErrorInfo(result.desc);
          }
        });
      }
    }
});

app.controller("openNeedCtrl", [
  "$scope",
  "$rootScope",
  "$modalInstance",
  "$http",
  "$filter",
  "lodash",
  "items",
  function($scope, $rootScope, $modalInstance, $http, $filter, lodash, items) {
    $scope.creator = {};
    $scope.issueList = [];
    $scope.sltAccount = [];
    $scope.userList = [];
    $scope.brdList = [];

    initValue();
    getIssueList();
    getUserList();
    setIssueStatus();

    //初始化数据
    function initValue() {
      angular.forEach(issueUser, function(user) {
        user.crtname = user.name;
      });
      items.userItem = { name: items.user, crtname: items.user };
      $scope.info = items;
      $scope.issueUser = issueUser;
    }

    //获取业务线数据
    function getIssueList() {
      var url = sys_config_url + "/select/get?type=BRD_BUSINESS";
      $http.get(url).success(function(result) {
        if (result.code == "0") {
          if (result.data) {
            angular.forEach(result.data.BRD_BUSINESS, function(issue) {
              issue.crtname = issue.value;
            });
            items.typeItem = lodash.findWhere(result.data.BRD_BUSINESS, {
              key: items.type
            });
            $scope.issueList = result.data.BRD_BUSINESS;
          } else {
            $rootScope.toasterErrorInfo("获取业务线数据错误！");
          }
        } else {
          $rootScope.toasterErrorInfo(result.desc);
        }
      });
    }

    //获取用户集合（设置提出人和指派对象）
    function getUserList() {
      var url = beetle_auth_url + "/user/?token_id=" + getTokenId();
      $http.get(url).success(function(result) {
        if (result.success) {
          if (result.data) {
            $scope.userList = result.data;
            $scope.sltAccount .push( lodash.findWhere(result.data, {
              account: $scope.info.toAccount
            }));
            $scope.creator = lodash.findWhere(result.data, {
              account: $scope.info.creatorAccount
            });
          } else {
            $rootScope.toasterErrorInfo("获取用户数据错误！");
          }
        } else {
          $rootScope.toasterErrorInfo(result.msg);
        }
      });
    }

    //设置状态列表
    function setIssueStatus() {
      angular.forEach(cStatus, function(status) {
        status.crtname = status.name;
      });
      items.issueStatusItem = lodash.findWhere(cStatus, { key: items.status });
      $scope.issueStatus = cStatus;
    }


    $scope.cancelClick = function() {
      $modalInstance.dismiss("cancel");
    };
  }
]);